package com.ruohi.image;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageUtils
{
  public static void createThumbnail(String pathFile)
    throws IOException
  {
    createThumbnail(pathFile, 300);
  }

  public static void createThumbnail(String pathFile, int offset)
    throws IOException
  {
    if ((pathFile != null) && (!"".equals(pathFile)) && 
      (pathFile.indexOf(".") != -1)) {
      pathFile = pathFile.toLowerCase();

      String ex = pathFile.substring(pathFile.lastIndexOf("."));
      if ((ex.equals(".jpg")) || (ex.equals(".png")) || (ex.equals(".gif")) || 
        (ex.equals(".bmp")))
      {
        String fPath = pathFile;
        if (pathFile.lastIndexOf("\\") != -1) {
          fPath = pathFile.substring(0, pathFile.lastIndexOf("\\"));
        }
        if (pathFile.lastIndexOf("/") != -1) {
          fPath = pathFile.substring(0, pathFile.lastIndexOf("/"));
        }
        String bPath = pathFile;
        if (pathFile.lastIndexOf("\\") != -1) {
          bPath = pathFile.substring(pathFile.lastIndexOf("\\"));
        }
        if (pathFile.lastIndexOf("/") != -1) {
          bPath = pathFile.substring(pathFile.lastIndexOf("/"));
        }
        File fPathFile = new File(fPath + "/small");
        if (!fPathFile.exists()) {
          fPathFile.mkdir();
        }
        String path = fPath + "/small" + bPath;
        File oldFile = new File(pathFile);
        File newFile = new File(path);
        if (newFile.exists())
          newFile.delete();
        try
        {
          BufferedImage o = ImageIO.read(oldFile);
          if (o != null) {
            float width = o.getWidth();
            float height = o.getHeight();
            float scale = 0.0F;
            if (width > height) {
              scale = offset / width;
              width = offset;
              height = Math.round(height * scale);
              if (height == 0.0F)
                height = 1.0F;
            }
            else {
              scale = offset / height;
              height = offset;
              width = Math.round(width * scale);
              if (width == 0.0F) {
                width = 1.0F;
              }
            }
            Thumbnails.of(new String[] { pathFile }).size((int)width, (int)height)
              .keepAspectRatio(false).outputQuality(1.0F)
              .toFile(newFile);
            if (o != null)
              o.flush();
          }
        }
        catch (Exception e) {
          e.printStackTrace();
          try
          {
            int bytesum = 0;
            int byteread = 0;
            InputStream inStream = new FileInputStream(pathFile);
            FileOutputStream fs = new FileOutputStream(path);
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
              bytesum += byteread;
              fs.write(buffer, 0, byteread);
            }
            fs.close();
            inStream.close();
          } catch (Exception e2) {
            e2.printStackTrace();
          }
        }
      }
    }
  }

  public static boolean resizeImg(File imgFile)
    throws IOException
  {
    return resizeImg(imgFile, 1000, 1000);
  }

  public static void resizeImgByHeight(File imgFile, int toHeight)
  {
    try
    {
      BufferedImage o = ImageIO.read(imgFile);
      if (o != null) {
        float width = o.getWidth();
        float height = o.getHeight();
        float scale = 0.0F;
        scale = toHeight / height;
        height = toHeight;
        width = Math.round(width * scale);
        if (width == 0.0F) {
          width = 1.0F;
        }
        Thumbnails.of(new File[] { imgFile }).size((int)width, (int)height)
          .keepAspectRatio(false).outputQuality(1.0F).toFile(
          imgFile);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void resizeImgByWidth(File imgFile, int toWidth)
  {
    try
    {
      BufferedImage o = ImageIO.read(imgFile);
      if (o != null) {
        float width = o.getWidth();
        float height = o.getHeight();
        float scale = 0.0F;
        scale = toWidth / width;
        width = toWidth;
        height = Math.round(height * scale);
        if (height == 0.0F) {
          height = 1.0F;
        }
        Thumbnails.of(new File[] { imgFile }).size((int)width, (int)height)
          .keepAspectRatio(false).outputQuality(1.0F).toFile(
          imgFile);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static boolean resizeImg(File imgFile, int maxWidth, int maxHeight)
    throws IOException
  {
    boolean isResize = false;
    try {
      BufferedImage o = ImageIO.read(imgFile);
      if (o != null) {
        float width = o.getWidth();
        float height = o.getHeight();
        float scale = 0.0F;
        if (width > height) {
          if (width > maxWidth) {
            isResize = true;
            scale = maxWidth / width;
            width = maxWidth;
            height = Math.round(height * scale);
            if (height == 0.0F) {
              height = 1.0F;
            }
          }
        }
        else if (height > maxHeight) {
          isResize = true;
          scale = maxHeight / height;
          height = maxHeight;
          width = Math.round(width * scale);
          if (width == 0.0F) {
            width = 1.0F;
          }
        }

        if (isResize)
          Thumbnails.of(new File[] { imgFile }).size((int)width, (int)height)
            .keepAspectRatio(false).outputQuality(1.0F).toFile(
            imgFile);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return isResize;
  }

  public static Map<String, Long> getImgInfo(String imgpath)
  {
    Map map = new HashMap(3);
    File imgfile = new File(imgpath);
    try {
      FileInputStream fis = new FileInputStream(imgfile);
      BufferedImage buff = ImageIO.read(imgfile);
      map.put("w", Long.valueOf(buff.getWidth() * 1L));
      map.put("h", Long.valueOf(buff.getHeight() * 1L));
      map.put("s", Long.valueOf(imgfile.length()));
      fis.close();
    } catch (FileNotFoundException e) {
      System.err.println("所给的图片文件" + imgfile.getPath() + 
        "不存在！计算图片尺寸大小信息失败！");
      map = null;
    } catch (IOException e) {
      System.err.println("计算图片" + imgfile.getPath() + "尺寸大小信息失败！");
      map = null;
    }
    return map;
  }

  public static void resizeFoderAllImg(List<String> ex, File folder)
    throws IOException
  {
    File[] files = folder.listFiles();
    String exStr = "";
    for (int i = 0; i < files.length; i++)
      if (files[i].isDirectory()) {
        resizeFoderAllImg(ex, files[i]);
      } else {
        exStr = files[i].getName().substring(
          files[i].getName().indexOf("."));
        if (ex.contains(exStr))
          resizeImg(files[i]);
      }
  }

  public static void createSmallFoderAllImg(List<String> ex, File folder)
    throws IOException
  {
    File[] files = folder.listFiles();
    String exStr = "";
    for (int i = 0; i < files.length; i++)
      if (files[i].isDirectory()) {
        resizeFoderAllImg(ex, files[i]);
      } else {
        exStr = files[i].getName().substring(
          files[i].getName().indexOf("."));
        if (ex.contains(exStr))
          createThumbnail(files[i].getAbsolutePath());
      }
  }

  public static final void pressImage(String pressImg, String targetImg)
  {
    pressImage(pressImg, targetImg, Positions.BOTTOM_RIGHT);
  }

  public static final void pressImage(String pressImg, String targetImg, Positions positions)
  {
    try
    {
      File _file = new File(targetImg);
      Image src = ImageIO.read(_file);
      int width = src.getWidth(null);
      int height = src.getHeight(null);
      Thumbnails.of(new File[] { _file }).size(width, height).keepAspectRatio(false)
        .watermark(positions, ImageIO.read(new File(pressImg)), 1.0F)
        .outputQuality(1.0F).toFile(_file);
      src.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}